package session;

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Query;

import entity.User;

/**
 * Dao bean klasa za entitet User
 * 
 * @author rigo
 *
 */
@Stateless
@Remote(UserDao.class)
public class UserDaoBean extends GenericDaoBean<User, Integer>  implements UserDao{
	
	@Override
	public User login(String email, String password) {
		try{
			Query q = em.createQuery("SELECT u FROM User u WHERE u.email=:ema AND u.password=:pass AND u.deleted=0 AND u.active=1");
			q.setParameter("ema", email);
			q.setParameter("pass", password);
			return (User)q.getSingleResult();
		}catch(Exception e){
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAllActive() {
		try{
			Query q = em.createQuery("SELECT u FROM User u WHERE u.deleted=0 AND u.active=1 ORDER BY u.firstName ASC, u.lastName ASC");
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}

	@Override
	public void deleteUser(Integer userId) {
		User usr = findById(userId);
		usr.setDeleted(true);
		merge(usr);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getPendingUsers() {
		try{
			Query q = em.createQuery("SELECT u FROM User u WHERE u.deleted=0 AND u.active=0");
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}

	@Override
	public void activateUser(Integer userId) {
		User usr = findById(userId);
		usr.setActive(true);
		merge(usr);	
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getScoreRanking() {
		try{
			Query q = em.createQuery("SELECT u FROM User u WHERE u.deleted=0 AND u.active=1 AND u.goals>0 ORDER BY u.goals DESC");
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}

	@Override
	public boolean isUserExists(String email) {
		try{
			Query q = em.createQuery("SELECT u FROM User u WHERE u.email=:ema AND u.deleted = 0");
			q.setParameter("ema", email);
			User u = (User)q.getSingleResult();
			if(u!=null) {
				return true;
			} else {
				return false;
			}
		}catch(Exception e){
			return false;
		}
	}
}
